import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-11-27
 * Time:15:06
 */
@WebServlet("/getParameter")
public class GetParameterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取 query string 中的键值对
        //假设浏览器的请求形如 ?studentId=10&studentName=张三
        //getParameter:以字符串形式返回请求参数的值，或者如果参数不存在则返回null;如果键存在,值不存在,得到的就是""
        String studentId = req.getParameter("studentId");
        String studentName = req.getParameter("studentName");
        System.out.println(studentId);
        System.out.println(studentName);

        //下面两行的代码顺序不能反:务必要保证先设置所有的header,最后再设置body
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(studentId + ", " + studentName);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过body 获取,发个 post 请求
        //预期请求的body请求形如 ?studentId=10&studentName=张三

        //请求这里设置的utf8 是告诉servlet(tomcat)如何解析
        req.setCharacterEncoding("utf8");
        String studentId = req.getParameter("studentId");
        String studentName = req.getParameter("studentName");
        System.out.println(studentId);
        System.out.println(studentName);

        //响应这里设置的utf8 是告诉浏览器如何解析
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(studentId + ", " + studentName);
    }
}
